import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/home/order/order_model.dart';

class OrderViewModel extends BaseViewModel {
  //数据源
  Map<String, List<OrderModel>> dataMap = {};

  Map<String, int> pageNumMap = {};

  Map<String, bool> isHaveMap = {};

  @override
  requestData({
    Function(dynamic)? onSuccess,
    Function(dynamic)? onError,
    String? orderStatus,
    bool isFrist = true,
  }) async {
    //分页查询
    int pageNum = pageNumMap[orderStatus] ?? 1;

    //默认没有更多数据
    bool isHaveData = isHaveMap[orderStatus] ?? true;

    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.anmoV2OrderList,
        method: DioHttpManager.post,
        data: {"page": pageNum, "limit": MyConstant.pageSize, "member_type": "0", "order_status": orderStatus});
    if (isFrist) {
      setState(ViewState.loading);
      pageNum = 0;
      isHaveData = true;
      dataMap[orderStatus!] = [];
    }
    if (resultMap['code'] == 0) {
      // 请求成功
      Map<String, dynamic> resultDataMap = resultMap['data'];
      List<dynamic> orderList = resultDataMap["list"] ?? [];

      if (orderList.length < MyConstant.pageSize) {
        isHaveData = true;
      } else {
        isHaveData = false;
      }

      List<OrderModel> dataList = dataMap[orderStatus!] ?? [];
      for (var element in orderList) {
        OrderModel orderModel = OrderModel.fromMap(element);
        dataList.add(orderModel);
      }
      dataMap[orderStatus] = dataList;

      pageNum += 1;
      pageNumMap[orderStatus] = pageNum;
      isHaveMap[orderStatus] = isHaveData;

      // 判断是否还有更多数据
      if (orderList.length < MyConstant.pageSize) {
        isHaveMap[orderStatus] = false;
      } else {
        isHaveMap[orderStatus] = true;
      }
      if (orderList.isEmpty) {
        setState(ViewState.empty);
        return;
      }
      //刷页面
      setState(ViewState.normal);
    } else {
      setState(ViewState.empty);
    }
  }
}
